import { useState, useRef, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import classNames from 'classnames'
import {
  todoDel,
  todoModifyName,
  todoModifyStatus,
} from '../../store/actions/todo'

export default function TodoItem({ item }) {
  const dispatch = useDispatch()
  const inputRef = useRef(null)
  const handleDel = (id) => dispatch(todoDel(id))
  const handleChange = (id) => dispatch(todoModifyStatus(id))
  const [currentId, setCurrentId] = useState('')
  const [currentName, setCurrentName] = useState('')
  const handleDblClick = (id) => {
    setCurrentId(id)
    setCurrentName(item.name)
  }
  const handleBlur = () => {
    setCurrentId('')
    setCurrentName('')
  }
  const handleNameChange = (e) => setCurrentName(e.target.value)
  const handleKeyUp = (e) => {
    if (e.keyCode === 27) {
      setCurrentId('') // 隐藏输入框
      setCurrentName('') // 当输入完之后 name 置为初始状态
      return
    }
    if (e.key === 'Enter') {
      if (currentName.trim().length === 0) return alert('不能为空')
      dispatch(todoModifyName(currentId, currentName))
      setCurrentId('')
      setCurrentName('')
    }
  }
  useEffect(() => inputRef.current.focus(), [currentId])
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: item.id === currentId,
      })}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => handleChange(item.id)}
        />
        <label onDoubleClick={() => handleDblClick(item.id)}>{item.name}</label>
        <button className='destroy' onClick={() => handleDel(item.id)}></button>
      </div>
      <input
        ref={inputRef}
        className='edit'
        value={currentName}
        onBlur={handleBlur}
        onChange={handleNameChange}
        onKeyUp={handleKeyUp}
      />
    </li>
  )
}
